import axios from 'axios'
export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    getList (state, data) {
      state.list = data
    },
    updateNum (state, num) {
      const row = state.list.find(item => item.id === num.id)
      if (num.num === -1 && row.goods_count === 1) return
      row.goods_count += num.num
    },
    updateState (state, id) {
      const row = state.list.find(item => item.id === id)
      row.goods_state = !row.goods_state
    },
    updateAllState (state, isFull) {
      state.list.forEach(item => (item.goods_state = isFull))
    }
  },
  actions: {
    async initState (store) {
      const { data } = await axios.get('http://www.itcbc.com:3006/api/cart')
      console.log(data)
      store.commit('getList', data.list)
    }
  },
  getters: {
    total (state) {
      const rows = state.list.filter(item => item.goods_state)
      return rows.reduce((n1, n2) => n1 + n2.goods_count, 0)
    },
    amount (state) {
      const rows = state.list.filter(item => item.goods_state)
      return rows.reduce((n1, n2) => n1 + n2.goods_price * n2.goods_count, 0)
    },
    isFull (state) {
      return state.list.every(item => item.goods_state)
    }
  }
}
